<template>
  <div class="wrap">
    <div class="search">
      <input type="text" class="search-input" placeholder="请输入要选择的城市" v-model="keyword">
    </div>
    <div class="search-content" v-show= "keyword" ref="wrapper">
      <ul class="search-list">
        <li class="list border-bottom" v-for="item of list" :key="item.id" @click = "handleClick(item.name)">{{item.name}}</li>
        <li class= "list list-tip" v-show = "showTip">没有查询到该城市</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  props: {
    cities: Object
  },
  mounted(){
    const scroll = new BScroll(this.$refs.wrapper)
  },
  data() {
    return {
      list: [],
      keyword: "",
      timer: null
    };
  },
  methods:{
    ...mapMutations(['changeCity']),
    handleClick(city){
      this.changeCity(city)
      // this.$store.commit('changeCity',city)
      this.$router.push('/')
    }
  },
  watch: {
    keyword() {
      if (!this.keyword) {
        this.list = [];
        return;
      }
      const result = [];
      if(this.timer){
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        for (let key in this.cities) {
          this.cities[key].forEach(val => {
            if (
              val.spell.indexOf(this.keyword) > -1 ||
              val.name.indexOf(this.keyword) > -1
            ) {
              result.push(val);
            }
          });
        }
      },50);
      this.list = result;
    }
  },
  computed: {
    showTip(){
      if(this.keyword && this.list.length === 0){
        return true
      }
    }
  }
};
</script>
<style lang="less" scoped>
@import "~styles/varibles.less";
.search {
  background-color: @bgColor;
  padding: 0.1rem;
  height: 0.72rem;
  .search-input {
    box-sizing: border-box;
    width: 100%;
    height: 0.62rem;
    padding: 0 0.1rem;
    margin-top: 0.06rem;
    border-radius: 0.06rem;
    text-align: center;
    color: #666;
    line-height: 0.62rem;
  }
}
.search-content {
  z-index: 1;
  overflow: hidden;
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 1.78rem;
  background-color:#fff;
  .search-list{
    .list{
      line-height: .68rem;
      padding: 0 .2rem;
    }
  }
}
</style>